import tkinter as tk
from tkinter import filedialog, messagebox
import os
import matplotlib.pyplot as plt

# 全局变量，用于存储提取的数据
data_lists = []

# 选择文件夹的函数
def select_folder():
    folder_path = filedialog.askdirectory()
    if folder_path:
        folder_entry.delete(0, tk.END)
        folder_entry.insert(0, folder_path)

# 提取数据的函数
def extract_data():
    global data_lists
    data_lists = []  # 清空之前的数据
    folder_path = folder_entry.get()
    if not folder_path:
        messagebox.showwarning("警告", "请先选择文件夹！")
        return

    # 获取文件夹下所有的.log文件
    log_files = [f for f in os.listdir(folder_path) if f.endswith('.log')]
    if not log_files:
        messagebox.showwarning("警告", "文件夹中没有找到.log文件！")
        return

    # 遍历每个.log文件
    for log_file in log_files:
        file_path = os.path.join(folder_path, log_file)
        try:
            with open(file_path, 'r') as file:
                lines = file.readlines()
                # 提取第一个逗号和第二个逗号之间的数据
                data_list = []
                for line in lines:
                    try:
                        # 找到第一个逗号和第二个逗号的位置
                        first_comma = line.find(',')
                        second_comma = line.find(',', first_comma + 1)
                        if first_comma != -1 and second_comma != -1:
                            data = line[first_comma + 1:second_comma].strip()
                            if data:  # 确保数据不为空
                                data_list.append(float(data))
                    except ValueError as e:
                        print(f"文件 {log_file} 中有一行数据格式错误: {line.strip()}")
                # 将提取的数据存储在按照文件读取顺序命名的列表中
                data_lists.append(data_list)
        except Exception as e:
            print(f"读取文件 {log_file} 时出错: {e}")

    # messagebox.showinfo("完成", "数据提取完成！")

# 绘图并保存的函数
def plot_and_save():
    extract_data()
    global data_lists
    if not data_lists:
        messagebox.showwarning("警告", "请先提取数据！")
        return

    # 确保所有列表长度一致
    min_length = min(len(lst) for lst in data_lists)
    if min_length == 0:
        messagebox.showwarning("警告", "提取的数据为空！")
        return

    # 按照下标顺序相加并除以4096
    result = [0] * min_length
    for lst in data_lists:
        for i in range(min_length):
            result[i] += lst[i]
    result = [x / 4096 for x in result]

    # 绘图
    plt.figure()
    plt.plot(result, marker='o')
    plt.xlabel('time')
    plt.ylabel('IOPS')
    plt.title('Performance Result')

    # 保存图片
    save_path = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png")])
    if save_path:
        plt.savefig(save_path)
        messagebox.showinfo("完成", f"图片已保存为 {save_path}")
    plt.show()

# 创建主窗口
root = tk.Tk()
root.title(".log文件数据处理")

# 创建选择文件夹的UI
folder_label = tk.Label(root, text="选择文件夹:")
folder_label.grid(row=0, column=0, padx=5, pady=5)

folder_entry = tk.Entry(root, width=50)
folder_entry.grid(row=0, column=1, padx=5, pady=5)

browse_button = tk.Button(root, text="浏览", command=select_folder)
browse_button.grid(row=0, column=2, padx=5, pady=5)

# # 创建提取数据按钮
# extract_button = tk.Button(root, text="提取数据", command=extract_data)
# extract_button.grid(row=1, column=1, padx=5, pady=5)

# 创建绘图并保存按钮
plot_button = tk.Button(root, text="绘图并保存", command=plot_and_save)
plot_button.grid(row=2, column=1, padx=5, pady=5)

# 运行主循环
root.mainloop()